package com.flypigs.resubmit;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;

import java.util.List;

@Configuration
public class ResubmitConfig implements ImportAware {
    //客户自定义resolver
    @Autowired(required = false)
    List<ResubmitResolver> resubmitResolvers;

    private AnnotationAttributes enableResubmit;

    /**
     * 防重复提交 aop
     * @return
     */
    @Bean
    ResubmitAspect resubmitAspect(){
        return new ResubmitAspect();
    }

    @Bean
    ResubmitResolvers resubmitResolvers() {
        ResubmitResolvers resolvers = new ResubmitResolvers();
        //注册默认resolver
        resolvers.addResubmitResolver(new ExceptionResolver());
        //resolvers.addResubmitResolver(new PrintResolver());

        //由于想同时支持非spring boot项目，所以没有使用@ConditionalOnClass ，而是通过Class.forName来检查是否是web项目
        if(ClassUtils.isPresent("javax.servlet.Servlet.Servlet",this.getClass().getClassLoader())){
            resolvers.addResubmitResolver(new HttpStatusResolver());
        }
        //注册客户自定义resolver
        if(resubmitResolvers != null) {
            resolvers.addResubmitResolvers(resubmitResolvers);
        }
        resolvers.setDefaultResubmitResolver((ResubmitResolver)BeanUtils.instantiateClass(enableResubmit.getClass("defaultResolver")));
        return resolvers;
    }

    @Override
    public void setImportMetadata(AnnotationMetadata annotationMetadata) {
        enableResubmit = AnnotationAttributes.fromMap(
                annotationMetadata.getAnnotationAttributes(EnableResubmit.class.getName(), false));
    }

}
